package com.hyou.starter.autoconfigure.datasource.tomcat;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.hyou.starter.autoconfigure.datasource.MyDataSource;

/**
 * <pre>
 * 数据源配置。
 * 默认支持主从数据源配置，一般主库支持读写操作、从库只支持读操作。
 * </pre>
 *
 * @author FengChangshuo
 * @version 1.0.0 2018-03-21 17:28:33 初始创建
 */
@Configuration
@ConditionalOnClass(org.apache.tomcat.jdbc.pool.DataSource.class)
@ConditionalOnProperty(prefix = "hyou.datasource", name = "tomcat", matchIfMissing = true)
public class TomcatDataSourceAutoConfiguration {

    private static final Logger log = LoggerFactory.getLogger(TomcatDataSourceAutoConfiguration.class);
    
    /**
     * @return 数据源配置属性数据对象
     */
    @Bean
    @ConfigurationProperties(prefix = "hyou.datasource.tomcat")
    public TomcatDataSourceMapProp tomcatDataSourceMapProp() {
        return new TomcatDataSourceMapProp();
    }
    
    /**
     * @return 默认数据源
     */
    @Bean
    public String defaultDataSource() {
        return tomcatDataSourceMapProp().getDefaultDataSource();
    }
    
    @Bean
    public MyDataSource configDataSource(@Qualifier("tomcatDataSourceMapProp") TomcatDataSourceMapProp dsMapProp) {
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        for(Entry<String, TomcatDataSourceProp> entry : dsMapProp.getDataSourceMap().entrySet()){
            dataSourceMap.put(entry.getKey(), TomcatDataSourceUtil.makeDataSource(entry.getValue()));
        }
        log.info("dataSourceMap : {}", dataSourceMap);
        return new MyDataSource(dataSourceMap, dsMapProp.getDefaultDataSource());
    }

}
